import { KVType, UserCateInfo } from '@/pages/personnelEntry/interface';
import { ProColumnType } from '@ant-design/pro-table';
import { PersonnelEntryState as T } from '../../pages/personnelEntry/interface';

interface LabelMapping {
    key: string;
    value: string;
}

function transformArrayToEnum(enumList: KVType[], label: LabelMapping) {
    return enumList.reduce((result, item) => {
        // @ts-ignore
        result[item[label.value]] = item[label.key];
        return result;
    }, {});
}
/**
 * 对catalog接口的数据进行一次性注入
 *
 * ```ts
 * const columns = injectEnumByKey(
 *      [...],
 *      {
 *          data1: {
 *              a: 1,
 *              b: 2,
 *          },
 *          data2: {
 *              a: 1,
 *              b: 2,
 *          },
 *      },
 *      ['data1', ['data2_id', 'data2']]
 * )
 * ```
 * @param columns
 * @param datas
 * @param keys column的key和要上传的id可能不一样，需要映射
 * @returns
 */
export function injectEnumByKey<T, K = keyof T>(
    columns: ProColumnType<T>[],
    datas: any,
    keys: (K | [key: K, value: K])[],
    label = { key: 'name', value: 'id' },
): ProColumnType<T>[] {
    if (!datas) return columns;
    const mappingKey = keys.map((item) =>
        Array.isArray(item) ? item[0] : item,
    );
    return columns.map((item) => {
        const index = mappingKey.indexOf(item.key as any);
        if (index !== -1) {
            const keyByIndex = Array.isArray(keys[index])
                ? // @ts-ignore
                  keys[index][1]
                : keys[index];
            // @ts-ignore
            const values = datas[keyByIndex];
            return {
                ...item,
                valueEnum: transformArrayToEnum(
                    Array.isArray(values) ? values : [],
                    label,
                ),
            };
        }

        return item;
    });
}
